#
# $Id$
#
# RTEMS Project (http://www.rtems.org/)
# Copyright 2007 Chris Johns (chrisj@rtems.org)
# All rights reserved.
#
# This file is part of The Builder.
#
# The Builder is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# The Builder is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with The Builder; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# Log output to stdout and/or a file.
#

import os
import sys

import error

def output(text = os.linesep, log = None):
    """Output the text to a log if provided else send it to stdout."""
    if text is None:
        text = os.linesep
    if log:
        log.output(text)
    else:
        for l in text.replace(chr(13), '').splitlines():
            print l

class log:
    """Log output to stdout or a file."""
    def __init__(self, streams = None):
        self.fhs = []
        if streams:
            for s in streams:
                if s == 'stdout':
                    self.fhs.append(sys.stdout)
                elif s == 'stderr':
                    self.fhs.append(sys.stderr)
                else:
                    try:
                        self.fhs.append(file(s, 'w'))
                    except IOError, ioe:
                         raise error.general("creating log file '" + s + \
                                             "': " + str(ioe))

    def __del__(self):
        for f in range(0, len(self.fhs)):
            if not self.fhs[f] in (sys.stdout, sys.stderr):
                self.fhs[f].close()

    def output(self, text):
        """Output the text message to all the logs."""
        # Reformat the text to have local line types.
        out = ''
        for l in text.replace(chr(13), '').splitlines():
            out += l + os.linesep 
        for f in range(0, len(self.fhs)):
            self.fhs[f].write(out)

    def flush(self):
        """Flush the output."""
        for f in range(0, len(self.fhs)):
            self.fhs[f].flush()
        
if __name__ == "__main__":
    l = log(['stdout', 'log.txt'])
    for i in range(0, 10):
        l.output('hello world\n')
    l.output('hello world CRLF\r\n')
    l.output('hello world NONE')
    l.flush()
    del l
